//
//  HomeController.m
//  RentTable
//
//  Created by mac on 2024/11/28.
//

#import "HomeController.h"
#import "PoolTableView.h"
#import "HotTableCell.h"
#import "HomeTableDetailController.h"

@interface HomeController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UIScrollView *contentScollView;

@property (nonatomic, strong) UIImageView *homeBackImageView;
@property (nonatomic, strong) UIImageView *discountImageView;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray<RentModel *> *products;
@property (nonatomic, strong) NSArray *options;;
@property (nonatomic, strong) UIButton *dropdownButton;
@property (nonatomic, strong) UILabel *hotLabel;


@end

@implementation HomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self loadProductData];
    [self loadUI];

}



- (void)loadProductData {
    
    RentManager *rentManager = [RentManager sharedManager];
    NSMutableArray<RentModel *> *rentModels = [rentManager getAllRentModelsWithRentTypeEightBall];
    self.products = rentModels;
    
    self.options = @[@"中八", @"斯诺克", @"九球"];
}

- (void)loadUI {
    CGFloat contentHeight = 1190 * scaleH;
    self.contentScollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, spDeviceWidth, spDeviceHeight - 64)];
    self.contentScollView.contentSize = CGSizeMake(spDeviceWidth, contentHeight);
    self.contentScollView.showsHorizontalScrollIndicator = NO;
    self.contentScollView.showsVerticalScrollIndicator = NO;
    self.contentScollView.contentInset = UIEdgeInsetsZero;
    self.contentScollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.view addSubview:self.contentScollView];
    
    self.homeBackImageView = [UIImageView new];
    self.homeBackImageView.image = [UIImage imageNamed:@"首页-bg"];
    self.homeBackImageView.contentMode = UIViewContentModeScaleAspectFill; // 确保图片填充
    [self.contentScollView addSubview:self.homeBackImageView];
    [self.homeBackImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.contentScollView);
        make.width.mas_equalTo(spDeviceWidth);
    }];
    [self.homeBackImageView setUserInteractionEnabled:true];
    
    
    self.discountImageView = [UIImageView new];
    self.discountImageView.image = [UIImage imageNamed:@"优惠-卡片"];
    [self.homeBackImageView addSubview:self.discountImageView];
    [self.discountImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(387 * scaleH);
        make.leading.mas_equalTo(16);
        make.trailing.mas_equalTo(-16);
        make.height.mas_equalTo(200 * scaleH);
    }];
    
    [self.discountImageView setUserInteractionEnabled:true];
    [self.homeBackImageView setUserInteractionEnabled:true];
    [self.contentScollView setUserInteractionEnabled:true];
    
    UILabel *welfareDisLabel = [UILabel new];
    welfareDisLabel.text = @"福利优惠";
    welfareDisLabel.font = [UIFont pingFangSCSemiboldWithSize:17];
    welfareDisLabel.textColor = myRGBHex(0x333333);
    [self.discountImageView addSubview:welfareDisLabel];
    [welfareDisLabel sizeToFit];
    [welfareDisLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(18);
        make.top.mas_equalTo(11);
        make.height.mas_equalTo(21);
    }];
    
    UILabel *newDisLabel = [UILabel new];
    newDisLabel.text = @"新人首次优惠惊喜！";
    newDisLabel.font = [UIFont pingFangSCMediumWithSize:13];
    newDisLabel.textColor = myRGBHex(0xFFFFFF);
    [self.discountImageView addSubview:newDisLabel];
    [newDisLabel sizeToFit];
    [newDisLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(welfareDisLabel.mas_trailing).offset(32 * scaleW);
        make.centerY.equalTo(welfareDisLabel.mas_centerY);
        make.height.mas_equalTo(18);
    }];
    
    NSMutableArray *poolImageItem = @[].mutableCopy;
    [poolImageItem addObjectsFromArray:[self.products subarrayWithRange:NSMakeRange(0, MIN(3, self.products.count))]];
    CGFloat top = 63 *scaleH;
    CGFloat width = 100 * scaleW;
    CGFloat height = 120 * scaleH;
    CGFloat origx = 10 * scaleW;
    CGFloat gap = (spDeviceWidth - 52 * scaleW - width * 3) / 3.0;
    
    UIStackView *stackView = [[UIStackView alloc] init];
    stackView.axis = UILayoutConstraintAxisHorizontal;
    stackView.spacing = gap;
    [stackView setUserInteractionEnabled:true];
    stackView.alignment = UIStackViewAlignmentCenter;
    stackView.distribution = UIStackViewDistributionEqualSpacing;
    
    for (NSInteger i = 0; i < 3; i++) {
        PoolTableView *tableview = [PoolTableView new];
        tableview.rentModel = poolImageItem[i];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableviewTapped:)];
        [tableview addGestureRecognizer:tapGesture];
        [stackView addArrangedSubview:tableview];
    }
    
    [self.discountImageView addSubview:stackView];
    stackView.frame = CGRectMake(origx, top, spDeviceWidth - 52 * scaleW, height);
    
    UIImageView *hotGoodImageview = [UIImageView new];
    hotGoodImageview.image = [UIImage imageNamed:@"热租卡片"];
    [self.homeBackImageView addSubview:hotGoodImageview];
    [hotGoodImageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.discountImageView.mas_bottom).offset(24);
        make.leading.mas_equalTo(16);
        make.trailing.mas_equalTo(-16);
        make.height.mas_equalTo(150 * scaleH);
    }];
    [hotGoodImageview setUserInteractionEnabled:true];
    
    UIView *hotBackView = [UIView new];
    hotBackView.layer.cornerRadius = 20;
    hotBackView.layer.masksToBounds = true;
    hotBackView.backgroundColor = myRGBHex(0xFFFFFF);
    [self.homeBackImageView addSubview:hotBackView];
    [hotBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(hotGoodImageview.mas_top).offset(55);
        make.leading.mas_equalTo(16);
        make.trailing.mas_equalTo(-16);
        make.height.mas_equalTo(450 * scaleH);
    }];
    [hotBackView setUserInteractionEnabled:true];
    
    UILabel *hotLabel = [UILabel new];
    hotLabel.text = @"中八台球桌";
    hotLabel.font = [UIFont pingFangSCSemiboldWithSize:24];
    hotLabel.textColor = myRGBHex(0x333333);
    hotLabel.textAlignment = NSTextAlignmentCenter;
    [hotBackView addSubview:hotLabel];
    [hotLabel sizeToFit];
    [hotLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(23 * scaleH);
        make.centerX.mas_equalTo(0);
        make.height.mas_equalTo(25);
    }];
    self.hotLabel = hotLabel;
    [self setDropButton:hotGoodImageview];
    [self setupCollectionView:hotBackView];
}

- (void)tableviewTapped:(UITapGestureRecognizer *)gestureRecognizer {
    PoolTableView *tappedTableView = (PoolTableView *)gestureRecognizer.view;
    RentModel *model = tappedTableView.rentModel;
    
    HomeTableDetailController *vc = [HomeTableDetailController new];
    vc.rentModel = model;
    vc.hidesBottomBarWhenPushed = true;
    [self.navigationController pushViewController:vc animated:true];
}


- (void)setDropButton:(UIView *)hotBackView {
    UIButton *dropdownButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [dropdownButton setTitle:@"中八" forState:UIControlStateNormal];
    [dropdownButton setTitleColor:myRGBHex(0x333333) forState:UIControlStateNormal];
    dropdownButton.titleLabel.font = [UIFont pingFangSCMediumWithSize:11];
    dropdownButton.backgroundColor = myRGBHex(0xFFFFFF);
    dropdownButton.layer.cornerRadius = 12;
    dropdownButton.layer.masksToBounds = YES;

    [hotBackView addSubview:dropdownButton];
    [dropdownButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(19 * scaleH);
        make.trailing.mas_equalTo(-12);
        make.size.mas_equalTo(CGSizeMake(78, 24));
    }];
    
    UIImageView *arrowImageView = [UIImageView new];
    arrowImageView.image = [UIImage imageNamed:@"通用_箭头"];
    [dropdownButton addSubview:arrowImageView];
    [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(12,12));
        make.trailing.mas_equalTo(-8);
    }];
    
    dropdownButton.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10);
    dropdownButton.imageEdgeInsets = UIEdgeInsetsMake(0, 50, 0, -10);

    [dropdownButton addTarget:self action:@selector(showOptions) forControlEvents:UIControlEventTouchUpInside];
    
    self.dropdownButton = dropdownButton;
}

- (void)setupCollectionView:(UIView *)hotBackView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((spDeviceWidth - 76) / 2.0, 185 * scaleH);
    layout.sectionInset = UIEdgeInsetsMake(10, 16, 10, 16);
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[HotTableCell class] forCellWithReuseIdentifier:@"HotTableCell"];
    
    [hotBackView addSubview:self.collectionView];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(59 * scaleH);
        make.leading.trailing.bottom.mas_equalTo(0);
    }];
}

#pragma mark - UICollectionViewDelegate & DataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.products.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HotTableCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotTableCell" forIndexPath:indexPath];
    
    RentModel *product = self.products[indexPath.item];
    
    [cell setPrice:[NSString stringWithFormat:@"%.1f", product.rentPrice] describe:product.rentTitle image:product.rentImage];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"234");
    
    HomeTableDetailController *vc = [HomeTableDetailController new];
    RentModel *product = self.products[indexPath.item];
    vc.rentModel = product;
    vc.hidesBottomBarWhenPushed = true;
    [self.navigationController pushViewController:vc animated:true];
}

- (void)showOptions {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    
    for (NSString *option in self.options) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:option
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * _Nonnull action) {
            [self.dropdownButton setTitle:option forState:UIControlStateNormal];
            
            [self updateTabData:option];
            
        }];
        [alertController addAction:action];
    }
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
//@[@"中八", @"斯诺克", @"九球"];
- (void)updateTabData:(NSString *)option {
    RentManager *rentManager = [RentManager sharedManager];
    NSMutableArray<RentModel *> *rentModels = @[].mutableCopy;
    if ([option isEqualToString:@"中八"]) {
        NSMutableArray *modelItem = [rentManager getAllRentModelsWithRentTypeEightBall];
        [rentModels addObjectsFromArray:modelItem];
    }else if ([option isEqualToString:@"斯诺克"]) {
        NSMutableArray *modelItem = [rentManager getAllRentModelsWithRentTypeSnooker];
        [rentModels addObjectsFromArray:modelItem];
    }else if ([option isEqualToString:@"九球"]) {
        NSMutableArray *modelItem = [rentManager getAllRentModelsWithRentTypeNineBall];
        [rentModels addObjectsFromArray:modelItem];
    }
    self.hotLabel.text = [NSString stringWithFormat:@"%@台球桌",option];
    self.products = rentModels;
    [self.collectionView reloadData];
}


@end
